package com.xrun.risk.service.process;

import com.xrun.ocenengine.dto.vo.AgentTokenAndTypeVo;
import com.xrun.risk.domain.WfRiskDeleteTask;
import com.xrun.risk.domain.WfRiskDeleteTaskAdter;
import com.xrun.risk.mapper.WfRiskDeleteTaskAdterMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@Slf4j
@Service
public class ProcessExecutorService {

      private final List<Process> processImplementations;
      	private final Executor executor = new ThreadPoolExecutor(5, 5,
			0L, TimeUnit.MILLISECONDS,   new LinkedBlockingQueue<Runnable>());

        @Autowired
        private WfRiskDeleteTaskAdterMapper wfRiskDeleteTaskAdterMapper ;


    // 构造函数注入所有Process实现
    @Autowired
    public ProcessExecutorService(List<Process> processImplementations) {
        this.processImplementations = processImplementations;
    }

    // 执行所有Process实现的execute方法
    // 使用CompletableFuture并发执行所有Process实现的execute方法并返回结果
    public Map<String, Object> executeAll(WfRiskDeleteTask wfRiskDeleteTask,
                                         WfRiskDeleteTaskAdter record,
                                          AgentTokenAndTypeVo vo) {
        Map<String, Object> hashMap = new HashMap<>();
        CountDownLatch countDownLatch = new CountDownLatch(processImplementations.size());
        for (Process process : processImplementations) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {

                        Object execute = process.execute(wfRiskDeleteTask, record,vo);
                        hashMap.put(process.getClass().getSimpleName(),execute);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw  new RuntimeException(e) ;
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return hashMap ;
    }
/**
 *
      @Autowired
     ProcessExecutorService processExecutorService;
    使用方法：
    Map<String, Object> stringObjectMap = processExecutorService.executeAll("111", 222);
 *
 *
 */



}
